using System;
using Core.Player.DataModel;
using UnityEngine;

namespace Core.Player
{
    public class PlayerController : MonoBehaviour
    {
        public PlayerData playerData;

        #region Components

        private Rigidbody2D _rb;
        public PlayerCombatCtr CombatCtr { get; private set; }

        #endregion

        #region Private Variables

        private Vector2 _input;
        private Vector2 _moveDirection;
        private Vector2 _orientation;
        private Vector2 _curMoveVelocity;
        private Vector2 _curRotateVelocity;

        #endregion

        #region Some Variables

        public MovementSpeed MovementSpeed => playerData.movementSpeed;
        public float PDeltaTime => Time.deltaTime;
        public float PFixedDeltaTime => Time.fixedDeltaTime;

        #endregion

        private void Awake()
        {
            _rb = GetComponent<Rigidbody2D>();
            CombatCtr = GetComponent<PlayerCombatCtr>();
        }

        public void Init()
        {
            
        }

        /// <summary>
        /// 控制移动
        /// </summary>
        /// <param name="input"></param>
        public void ControlMove(Vector2 input)
        {
            _input = input;

            if (_input == Vector2.zero)
            {
                _rb.velocity = Vector2.SmoothDamp(_rb.velocity, Vector2.zero, ref _curMoveVelocity,
                    MovementSpeed.stopMoveSmoothTime,
                    MovementSpeed.moveDecelerationSpeed);
                return;
            }

            _moveDirection = _input;
            _rb.velocity = _moveDirection * playerData.movementSpeed.moveSpeed;
        }

        /// <summary>
        /// 根据鼠标方向控制旋转
        /// </summary>
        /// <param name="mousePos"></param>
        public void ControlRotate(Vector3 mousePos)
        {
            Vector3 toDirection = (mousePos - transform.position).normalized;
            toDirection.z = 0;
            _orientation = toDirection;
            float rotZ = Mathf.Atan2(_orientation.x, _orientation.y) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, 0, -rotZ),
                MovementSpeed.rotateSpeed * Time.deltaTime);
        }

#if UNITY_EDITOR
        private void OnDrawGizmos()
        {
            Gizmos.color = Color.green;
            Gizmos.DrawRay(transform.position, _orientation);
        }
#endif
        
    }
}
